<template>
  <div class="app-container">
    <el-button type="primary" @click="$router.back()">返回</el-button>
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployee } from '@/api/employees'
import { formatExcelDate } from '@/utils/index.js'
export default {
  name: 'Import',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    formatExcel(data) {
      // 1. 映射对象，根据映射对象找英文的键
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      // 2. 需要将数据中的中文的键的数据对象一个一个的遍历出来
      const result = data.map(item => {
        console.log(item)
        Object.keys(item) // ['入职日期', '姓名', '工号', '手机号', '转正日期', '部门']
        const new_obj = {}
        // 2. 根据映射对象，将中文的key转化为应为key
        Object.keys(item).forEach(zhKey => {
          console.log(zhKey)
          const enKey = mapInfo[zhKey]
          new_obj[enKey] = item[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            new_obj[enKey] = formatExcelDate(item[zhKey])
          } else {
            new_obj[enKey] = item[zhKey]
          }
        })
        return new_obj
      })
      return result
    },
    async doImport(data) {
      try {
        const res = await importEmployee(data)
        console.log('importEmployee', res)
        this.$message.success('导入成功')
        // 页面后退
        this.$router.back()
      } catch (err) {
        console.log('importEmployee', err)
        this.$message.error('导入失败')
      }
    },
    //  1. 把数据从excel文件读入到浏览器内存
    handleSuccess({ header, results }) {
      console.log(header, results)

      // 2. 按接口要求 组装数据
      const data = this.formatExcel(results)
      console.log('按接口要求 组装数据', data)
      // 3. 调用接口做上传
      this.doImport(data)
    }
  }
}
</script>
